#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/10/4 9:34
# @Author  : leon yan
# @Site    :
# @File    : TechnologyEdit.py
# @Software: PyCharm
import datetime
import json
import time

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from PyQt5.QtCore import pyqtSignal, pyqtSlot

from lib.qsqledit import QSQL, NewEditDb
from lib.qCreateQRCode import QCreateQRCode
import Globalist as gl
from resource.TechnologyEdit_ui import Ui_Form


class QTechnologyEdit(QWidget, Ui_Form):
    bUpdate = pyqtSignal()

    def __init__(self, DbId=None, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        self.DbId = DbId
        self.UserDb = {}
        self.QCreateQRCodeObj = QCreateQRCode()
        if self.DbId:
            '''Edit'''
            self.setWindowTitle("编辑工艺卡")
            dictWhere = {"id": DbId}
            aa = self.rdDetail("TechnologyTbl", dictWhere, 'equal', 1, None)[0][0]  # 读数据库
            self.Id.setText(str(aa[0]))
            self.barCode.setText(str(aa[1]))
            self.technologyInput.setText(str(aa[2]))
            self.materialInput.setText(str(aa[3]))
            self.spinHeight.setValue(aa[4])
            self.spinLenght.setValue(aa[5])
            self.spinWidth.setValue(aa[6])
            self.description.setText(str(aa[7]))
            '''QRCode'''
            self.QCreateQRCodeObj.do_QRCode(str(aa[1]), [6, 2, 1, "label"])
            pic = QPixmap(r".\.temp\qrcode.jpg")
            self.labQRImage.setPixmap(pic)
        else:
            '''New'''
            self.setWindowTitle("创建工艺卡")
            pass

    def __del__(self):
        print("TechnologyEdit is deleted")

    def rdDetail(self, tblName, dictCondition=None, strQueryType=None, eNum=None, strWhere=None):
        strOrder = ''
        aFields = ['id', 'Barcode', 'TechnologyName', 'Material', 'Height', 'Length', 'Width', 'Descriptions',
                   'CreateDate', 'Operator', 'Status']
        obj = QSQL(tblName, dictCondition, strOrder, aFields, strQueryType, eNum, strWhere)
        rdData = obj.showLst()
        jd = json.loads(rdData)
        return jd, len(jd)

    def readDB(self):
        aFields = ['id', 'Barcode', 'TechnologyName', 'Material', 'Height', 'Length', 'Width', 'Descriptions',
                   'CreateDate', 'Operator']
        obj = QSQL("TechnologyTbl", "", "", aFields)
        rdData = obj.showLst()
        retDataLst = json.loads(rdData)
        return retDataLst

    def writeDB(self, lst):
        retDataLst = NewEditDb("TechnologyTbl", lst)
        return retDataLst

    @pyqtSlot()
    def on_btnClose_clicked(self):
        self.close()

    @pyqtSlot()
    def on_btnApply_clicked(self):
        timeStamp = int(round(time.time() * 100000))
        barCode = str(timeStamp)
        technologyInput = self.technologyInput.text().strip()
        materialInput = self.materialInput.text().strip()
        spinHeight = self.spinHeight.value()
        spinLenght = self.spinLenght.value()
        spinWidth = self.spinWidth.value()
        description = self.description.text().strip()
        createDate = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
        if gl.get_value("LoginUser"):
            operator = gl.get_value("LoginUser")
        else:
            operator = ""
        status = "初始"

        '''新建'''
        if self.DbId is None:
            lst = [-1, barCode, technologyInput, materialInput, spinHeight, spinLenght, spinWidth,
                   description, createDate, operator, status]
            aa = self.writeDB(lst)
            if aa:
                QMessageBox.information(self, "Tips", "保存成功!")
            else:
                QMessageBox.warning(self, "warning", "保存失败!")
            self.bUpdate.emit()
            self.close()
        else:
            lst = [self.DbId, barCode, technologyInput, materialInput, spinHeight, spinLenght, spinWidth,
                   description, createDate, operator, status]
            aa = self.writeDB(lst)
            if aa:
                QMessageBox.information(self, "Tips", "保存成功!")
            else:
                QMessageBox.warning(self, "warning", "保存失败!")
            self.bUpdate.emit()
            self.close()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    EditUser_Form = QTechnologyEdit(None)

    EditUser_Form.show()
    sys.exit(app.exec_())
